package com.sherllinhe.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
//import com.sherllinhe.common.context.LoginMemberContext;
import com.sherllinhe.business.domain.*;
import com.sherllinhe.business.req.TrainStationQueryReq;
import com.sherllinhe.business.resp.TrainStationQueryResp;
import com.sherllinhe.common.resp.PageResp;
import com.sherllinhe.common.util.SnowUtil;
import com.sherllinhe.business.mapper.DailyTrainMapper;
import com.sherllinhe.business.req.DailyTrainQueryReq;
import com.sherllinhe.business.req.DailyTrainSaveReq;
import com.sherllinhe.business.resp.DailyTrainQueryResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 功能：
 * 作者：Sherllin He
 * 日期：
 */
@Slf4j
@Service
public class DailyTrainService {
    @Autowired
    private DailyTrainMapper dailyTrainMapper;
    @Autowired
    private TrainService trainService;
    @Autowired
    private DailyTrainStationService dailyTrainStationService;
    @Autowired
    private DailyTrainCarriageService dailyTrainCarriageService;
    @Autowired
    private DailyTrainSeatService dailyTrainSeatService;
    @Autowired
    private DailyTrainTicketService dailyTrainTicketService;
    @Autowired
    private SkTokenService skTokenService;
    // 新增和编辑每日车次
    public void save(DailyTrainSaveReq req){
        DateTime now = DateTime.now();
        DailyTrain dailyTrain = BeanUtil.copyProperties(req, DailyTrain.class);

        //判断是新增还是更新
        //dailyTrain.setMemberId(LoginMemberContext.getId());
        if(ObjUtil.isNull(dailyTrain.getId())) {
            //新增
            dailyTrain.setId(SnowUtil.getSnowflakeNextId());
            dailyTrain.setCreateTime(now);
            dailyTrain.setUpdateTime(now);
            dailyTrainMapper.insert(dailyTrain);
        }else{
            //更新
            dailyTrain.setUpdateTime(now);
            dailyTrainMapper.updateByPrimaryKey(dailyTrain);
        }


    }
    // 分页查询每日车次列表
    public PageResp<DailyTrainQueryResp> queryList(DailyTrainQueryReq req){
        DailyTrainExample example = new DailyTrainExample();
        example.setOrderByClause("date desc, code asc");

        DailyTrainExample.Criteria criteria = example.createCriteria();
        if(ObjUtil.isNotNull(req.getDate())){
            criteria.andDateEqualTo(req.getDate());
        }
        if(ObjUtil.isNotEmpty(req.getCode())){
            criteria.andCodeEqualTo(req.getCode());
        }

        log.info("查询页码:{}",req.getPage());
        log.info("每页条数:{}",req.getSize());
        PageHelper.startPage(req.getPage(),req.getSize());
        List<DailyTrain> dailyTrainList = dailyTrainMapper.selectByExample(example);

        PageInfo<DailyTrain> pageInfo = new PageInfo<>(dailyTrainList);
        log.info("总条数:{}", pageInfo.getTotal());
        log.info("总页数:{}", pageInfo.getPages());

        List<DailyTrainQueryResp> list = BeanUtil.copyToList(dailyTrainList, DailyTrainQueryResp.class);

        PageResp<DailyTrainQueryResp> pageResp = new PageResp<>();
        pageResp.setList(list);
        pageResp.setTotal(pageInfo.getTotal());

        return pageResp;
    }
    //删除每日车次
    public void delete(Long id){
        dailyTrainMapper.deleteByPrimaryKey(id);
    }

    /**
     * 生成某日所有车次信息，包括车次、车站、车厢、座位
     * @param date
     */
    @Transactional
    public void genDaily(Date date){
        List<Train> trainList = trainService.selectAll();
        if(CollUtil.isEmpty(trainList)){
            log.info("没有车次基础数据，任务结束");
            return;
        }
        for(Train train : trainList){
            log.info("生成日期：{}车次：{}的信息开始", DateUtil.formatDate(date), train.getCode());
            //生该车次的每日车次信息
            genDailyTrain(date, train);
            //生成该车次的每日车站信息
            dailyTrainStationService.genDailyStation(date, train.getCode());
            //生成该车次的每日车厢信息
            dailyTrainCarriageService.genDailyCarriage(date, train.getCode());
            //生成该车次的每日座位信息
            dailyTrainSeatService.genDailySeat(date, train.getCode());
            //生成该车次的每日余票信息
            dailyTrainTicketService.genDailyTicket(train, date, train.getCode());
            //生成令牌余量信息
            skTokenService.genDaily(date, train.getCode());
            log.info("生成日期：{}车次：{}的信息结束", DateUtil.formatDate(date), train.getCode());
        }
    }

    public void genDailyTrain(Date date, Train train){
        // 删除该车次已有的数据
        DailyTrainExample dailyTrainExample = new DailyTrainExample();
        dailyTrainExample.createCriteria()
                .andDateEqualTo(date)
                .andCodeEqualTo(train.getCode());
        dailyTrainMapper.deleteByExample(dailyTrainExample);
        // 生成该车次数据
        DailyTrain dailyTrain = BeanUtil.copyProperties(train, DailyTrain.class);
        dailyTrain.setId(SnowUtil.getSnowflakeNextId());
        dailyTrain.setDate(date);
        DateTime  now = DateTime.now();
        dailyTrain.setCreateTime(now);
        dailyTrain.setUpdateTime(now);
        dailyTrainMapper.insert(dailyTrain);
    }
}
